#include"laststage.h"
#include<fstream>
void last::set(Mapping_C* map)
{
	int line=1;
	map->getNode(node);
	for(unsigned int i=0;i<node.size();i++)
	{
		if(node[i]->id==8)
		{
			Net_C* w=new Net_C;
			w->name=node[i]->name;
			w->nline=-1;
			for(unsigned int j=0;j<node[i]->output.size();j++)
				node[i]->output[j]->inwire.push_back(w);
			node.erase(node.begin()+i);
			i--;
			iowire.push_back(w);
		}
		else if(node[i]->id==9)
		{
			Net_C* w=new Net_C;
			w->name=node[i]->name;
			w->nline=-1;
			for(unsigned int j=0;j<node[i]->input.size();j++)
				node[i]->input[j]->outwire=w;
			node.erase(node.begin()+i);
			i--;
			iowire.push_back(w);
		}
		else
		{
			Net_C* w=new Net_C;
			w->nline=line;
			node[i]->outwire=w;
			for(unsigned int j=0;j<node[i]->output.size();j++)
				node[i]->output[j]->inwire.push_back(w);
			wire.push_back(w);
			line++;
		}	
	}
	for(unsigned int i=0;i<node.size();i++)
	{
		if(node[i]->id==0)
			node[i]->name="not";
		else if(node[i]->id==1)
			node[i]->name="and";
		else if(node[i]->id==2)
			node[i]->name="buf";
		else if(node[i]->id==3)
			node[i]->name="nand";
		else if(node[i]->id==4)
			node[i]->name="or";
		else if(node[i]->id==5)
			node[i]->name="nor";
		else if(node[i]->id==6)
			node[i]->name="xor";
		else if(node[i]->id==7)
			node[i]->name="xnor";
	}
}

void last::dump(char* in_p,char* out_p)
{
	ofstream output;
	ifstream in;
	output.open(out_p);
	in.open(in_p);
	string  s;
	unsigned int n=0;
	in>>s;
	output<<s;
	while(s[0]!='w')
	{
		in>>s;
		output<<s;
		n++;
	}
	while(n>0)
	{
		output<<s;
		in>>s;
		n--;
	}
	n=1;
	output<<"wire ";
	while(n<=wire.size())
	{
		output<<"w"<<n<<",";
		if(n%10==0)
		{
			output<<";"<<endl;
			output<<"wire ";
		}
		n++;
	}
	output<<";"<<endl;
	n=0;
	while(n<node.size())
	{
		output<<"   "<<node[n]->name<<"(";
		if(node[n]->outwire->nline<0)
			output<<node[n]->outwire->name<<",";
		else
			output<<" w"<<node[n]->outwire->nline<<",";
		for(unsigned int i=0;i<node[n]->inwire.size();i++)
		{
			if(node[n]->inwire[i]->nline<0)
				output<<node[n]->inwire[i]->name;
			else
				output<<"w"<<node[n]->inwire[i]->nline;
			if(i!=node[n]->inwire.size()-1)
			output<<", ";
		}
		output<<");"<<endl;
	}	
	output<<"endmodule"<<endl;
	for(unsigned int i=0;i<wire.size();i++)
		delete wire[i];
	for(unsigned int i=0;i<iowire.size();i++)
		delete iowire[i];
	for(unsigned int i=0;i<node.size();i++)
		delete node[i];
}
